<template>
  <div id="invOrderlDiv">
    <Breadcrumb content="物品申领" />
    <div class="bodyContent">
      <Splitpanes>
        <Pane size="50">
          <vxe-form :data="searchForm" class="searchform form-input-m">
            <vxe-form-item title="单据日期[起]">
              <template #default="{ data }">
                <el-date-picker v-model="data.documentDateBegin" :value-format="'YYYY-MM-DD HH:mm:ss'" type="datetime" placeholder="单据日期[起]" :shortcuts="shortcuts" />
              </template>
            </vxe-form-item>
            <vxe-form-item title="单据日期[止]">
              <template #default="{ data }">
                <el-date-picker v-model="data.documentDateEnd" :value-format="'YYYY-MM-DD HH:mm:ss'" type="datetime" placeholder="单据日期[止]" :shortcuts="shortcuts" />
              </template>
            </vxe-form-item>
            <vxe-form-item title="流转单号">
              <vxe-input v-model="searchForm.transferNo" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findInvOrderList" @keyup="keyupEnter" @search-click="findInvOrderList()"></vxe-input>
            </vxe-form-item>
            <vxe-form-item title="单据状态">
              <vxe-select v-model="searchForm.orderStatus" :filterable="true" @change="orderStatusChangeEvent" clearable transfer>
                <vxe-option v-for="orderSObj in invOrderStatusList" :key="orderSObj.commonId" :value="orderSObj.code" :label="orderSObj.name"></vxe-option>
              </vxe-select>
            </vxe-form-item>
            <vxe-form-item>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-search" content="查询" :loading="tloading" @click="findInvOrderList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="申领制单" @click="addInvOrderDialog()"></vxe-button>
              <vxe-button type="text" v-show="orderForm.transferType=='R60'&&(orderForm.orderStatus=='0'||orderForm.orderStatus=='5')" class="button-blue" icon="vxe-icon-edit" content="修改" @click="editInvOrderDialog()"></vxe-button>
              <vxe-button type="text" v-show="orderForm.transferType=='C60'&&orderForm.orderStatus=='5'" class="button-blue" icon="vxe-icon-check" content="确认入库" @click="checkInStock()"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteInvReagent"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-print" content="打印" :loading="showLoading" @click="quietPrint"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-search" content="预览" :loading="showLoading" @click="previewPrint"></vxe-button>
            </vxe-form-item>
          </vxe-form>
          <div class="tableBoBox">
            <vxe-table ref="invOrderTableRef" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :data="invOrderList" :loading="tloading" @current-change="invOrderRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
              <vxe-column type="seq" title="序号" width="80"></vxe-column>
              <vxe-column field="orderStatus" title="状态" width="80">
                <template #default="{ row }">
                  <div class="justify-atart">
                    <span :class="getStatusClass(row)">
                      {{ formatCommon(invOrderStatusList, row.orderStatus) }}
                    </span>
                  </div>
                </template>
              </vxe-column>
              <vxe-column field="transferType" title="流转方式" width="80">
                <template #default="{ row }">
                  <span>
                    {{ formatTransType(transTypeList, row.transferType) }}
                  </span>
                </template>
              </vxe-column>
              <vxe-column field="transferNo" title="调库单号" width="200">
                <template #default="{ row }">
                  <span>{{ row.transferNo }}</span>
                </template>
              </vxe-column>
              <vxe-column field="tarStoreNa" title="申领仓库" width="100">
                <template #default="{ row }">
                  <span>{{ row.tarStoreNa }}</span>
                </template>
              </vxe-column>
              <vxe-column field="documentDate" title="制单日期" width="150"></vxe-column>
              <vxe-column field="storagePersonnel" title="制单人" width="100"></vxe-column>
              <vxe-column field="remake" title="备注" width="300">
                <template #default="{ row }">
                  <span>{{ row.remake }}</span>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <Pane size="50">
          <Splitpanes horizontal class="horizontalLine">
            <Pane size="40">
              <vxe-toolbar perfect>
                <template #buttons>
                  <div class="toolbartitle">申领详情</div>
                </template>
              </vxe-toolbar>
              <el-form ref="orderFormRef" :model="orderForm" label-width="100px" inline-message>
                <el-row>

                  <el-col :span="8"><el-form-item prop="tarStoreNa" label="仓库名称">
                      <el-input type="text" v-model="orderForm.tarStoreNa" placeholder="仓库名称"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8"><el-form-item prop="tarStoreNa" label="调库单号">
                      <el-input type="text" v-model="orderForm.transferNo" placeholder="调库单号"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8"><el-form-item prop="storagePersonnel" label="制单人">
                      <el-input type="text" v-model="orderForm.storagePersonnel" placeholder="调库人"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">

                    <el-form-item prop="receiveDate" label="领用日期">
                      <el-date-picker v-model="orderForm.receiveDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择日期" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8"><el-form-item prop="notifyPerson" label="确认人">
                      <el-input type="text" v-model="orderForm.notifyPerson" placeholder="请输入确认人"></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="8"><el-form-item prop="notifyDate" label="确认时间">
                      <el-input type="text" v-model="orderForm.notifyDate" placeholder="请输入确认时间"></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="24">
                    <el-form-item prop="remake" label="备注">
                      <el-input type="textarea" v-model="orderForm.remake" placeholder="请输入说明"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </Pane>
            <Pane size="60">
              <vxe-toolbar perfect>
                <template #buttons>
                  <div class="smallToolTitle">商品明细</div>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="iloading" :disabled="isEmpty(orderForm.id)" @click="findOrderReagentList"></vxe-button>
                </template>
              </vxe-toolbar>
              <div class="tableBox">
                <vxe-table ref="materialItemTableRef" class="mytable-scrollbar" border="inner" align="center" height="auto" :data="invOrderReagentList" :loading="iloading" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }" resizable show-overflow keep-source>
                  <vxe-column type="seq" title="序号" width="30"></vxe-column>
                  <vxe-column field="oriStoreNa" title="来源仓库" width="100"> </vxe-column>
                  <vxe-column field="reaNo" title="商品编号" width="100"> </vxe-column>
                  <vxe-column field="reaNa" title="商品名称" width="100"> </vxe-column>
                  <vxe-column field="specModel" title="规格型号" width="100"> </vxe-column>
                  <vxe-column field="unit" title="单位" width="100"> </vxe-column>
                  <vxe-column field="batchNum" title="批号" width="100"> </vxe-column>
                  <vxe-column field="amount" title="目标库存" width="100"> </vxe-column>
                  <vxe-column field="applyNum" title="申请数量" width="100"> </vxe-column>
                  <vxe-column field="applyNum" title="实发数量" width="100"> </vxe-column>
                  <vxe-column field="produceDate" title="生产日期" width="100"> </vxe-column>
                  <vxe-column field="expiryDate" title="有效期" width="100"> </vxe-column>
                </vxe-table>
              </div>
            </Pane>
          </Splitpanes>
        </Pane>
      </Splitpanes>
      <MultiRptPreviewFixId :reportList="reportList" :toggle="isPreviewRpt" :modalTitle="'入库单预览'" />

      <!-- 静默打印 -->
      <QuietPrint ref="quietPrintRef" :printParams="printParamsObj" />
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import moment from 'moment';
import { Splitpanes, Pane } from 'splitpanes';
import { formatDateTime } from '@/utils/common';
import MultiRptPreviewFixId from '@/components/MultiRptPreviewFixId.vue';
import QuietPrint from '@/components/QuietPrint.vue';

import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { isEmpty } from 'lodash';
import type { Length } from 'html2canvas/dist/types/css/types/length';
let { proxy }: any = getCurrentInstance();
let invOrderStatusList: any = reactive([]);
let transTypeList: any = reactive([]);
let invOrderList: any = reactive([]);
let invOrderReagentList: any = reactive([]);
let tloading = ref(false); //刷新加载状态
let iloading = ref(false); //刷新加载状态
let sltInvOrder: any = ref({});
let reportList = reactive([]);
const isPreviewRpt = ref(false);
let printParamsObj = ref(null);
let orderForm: any = reactive({
  id: null,
  supplierCode: '',
  supplierName: '',
  tarStoreNa: '',
  tarStoreCode: '',
  invoiceNumber: '',
  invoiceDate: '',
  documentDate: '',
  purOrderNumber: '',
  outOrderNumber: '',
  businessType: '',
  storagePersonnel: '',
  storageMark: '',
  notifyPerson: '',
  notifyDate: '',
  remake: '',
  seq: null,
  transferType: ''
});
let searchForm = reactive({
  searchValue: '',
  transferNo: '',
  transferType: 'R60',
  orderStatus: '',
  documentDateBegin: formatDateTime(new Date().setTime(new Date().getTime() - 3600 * 1000 * 24 * 7), 'yyyy-MM-dd 00:00:00'),
  documentDateEnd: formatDateTime(new Date(), 'yyyy-MM-dd 23:59:59')
});

const shortcuts = [
  {
    text: '今天',
    value: new Date()
  },
  {
    text: '昨天',
    value: () => {
      const date = new Date();
      date.setDate(date.getDate() - 1);
      return date;
    }
  },
  {
    text: '一周前',
    value: () => {
      const date = new Date();
      date.setDate(date.getDate() - 7);
      return date;
    }
  }
];

// 页面加载时更新报告单元/字典
onMounted(async () => {
  if (!isEmpty(proxy.$route.query.orderStatus)) {
    searchForm.orderStatus = proxy.$route.query.orderStatus.toString();
  }
  getDictItemsList(); //批量获取字典
  findInvTransTypeList();
  await findInvOrderList();
});

async function findInvTransTypeList() {
  const url = '/inv/transfer/type/findInvTransferTypeList';
  await proxy.$http
    //注意此处的数据条数
    .get(url)
    .then((res: any) => {
      if (res.status.code === 1) {
        transTypeList.push(...res.data);
      }
    })
    .catch((err: any) => {
      // VxeMessage('获取机构列表失败',VxeNotifyType.error)
    });
}
// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findInvOrderList();
  }
}

async function findInvOrderList() {
  tloading.value = true;
  invOrderList.length = 0; //放入数据前清空数据
  const url = '/inv/orderInfo/findOrderInfoList';
  await proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        searchValue: searchForm.searchValue,
        transferNo: searchForm.transferNo,
        transferTypes: 'R60,C60',
        orderStatus: searchForm.orderStatus,
        documentDateBegin: searchForm.documentDateBegin,
        documentDateEnd: searchForm.documentDateEnd
      }
    })
    .then((res: any) => {
      invOrderList.push(...res.data);
      if (invOrderList.length == 0) {
        sltInvOrder.value = {};
        clearOrderForm();
        invOrderReagentList.length = 0; //放入数据前清空数据
      } else {
        const kn = invOrderList.find((k: any) => k.id == sltInvOrder.value.id);
        if (isEmpty(kn)) {
          invOrderRowClick({ row: invOrderList[0] }); //默认选中第一条数据
        } else {
          invOrderRowClick({ row: kn }); //默认选中第一条数据
        }
      }

      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

// 点击质控品维护表格当前行触发右侧表单变化
function invOrderRowClick({ row }: any) {
  if (isEmpty(row)) {
    sltInvOrder.value = {};
    clearOrderForm();
  } else {
    (proxy.$refs.invOrderTableRef as any).setCurrentRow(row);
    sltInvOrder.value = row;
    setOrderForm(row);
  }
}

// 清空表单
function clearOrderForm() {
  orderForm.id = null;
  orderForm.supplierCode = '';
  orderForm.supplierName = '';
  orderForm.tarStoreNa = '';
  orderForm.tarStoreCode = '';
  orderForm.invoiceNumber = '';
  orderForm.invoiceDate = '';
  orderForm.documentDate = '';
  orderForm.purOrderNumber = '';
  orderForm.outOrderNumber = '';
  orderForm.businessType = '';
  orderForm.storagePersonnel = '';
  orderForm.storageMark = '';
  orderForm.notifyPerson = '';
  orderForm.notifyDate = '';
  orderForm.remake = '';
  orderForm.seq = null;
  orderForm.transferType = '';
}
//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['invOrderAllotStatus'];

  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });

  const iosObj = dictTreeTypeItems.data.find((item: any) => item.code === 'invOrderAllotStatus');
  invOrderStatusList.push(...iosObj.detailDataList);
}

function setOrderForm(row: any) {
  Object.assign(orderForm, row);
  findOrderReagentList(); // 获取最右侧 质控项目设定表格数据
}

// 获取最右侧 质控项目设定表格数据
function findOrderReagentList() {
  iloading.value = true;
  invOrderReagentList.length = 0; //放入数据前清空数据
  const url = '/inv/orderReagent/findOrderReagentList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { orderInfoId: orderForm.id }
    })
    .then((res: any) => {
      invOrderReagentList.push(...res.data);
      iloading.value = false;
    })
    .catch((err: any) => {
      iloading.value = false;
      VxeMessage('获取右侧获取质控项目表格数据异常', VxeNotifyType.error);
    });
}
function orderStatusChangeEvent() {
  findInvOrderList();
}
function deleteInvReagent() {
  if (orderForm.orderStatus != '5') {
    VxeMessage('请删除未验收的单据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const sltQcMaterials = [];
        sltQcMaterials.push(orderForm);
        const data = { invOrderInfoList: sltQcMaterials };
        const url = '/inv/orderInfo/batchDeleteInvOrderInfoList';
        proxy.$http
          .post(url, data)
          .then((res: any) => {
            findInvOrderList(); // 获取检验仪器表格数据
            VxeMessage(res.status.msg, VxeNotifyType.success);
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

function addInvOrderDialog() {
  const data = {
    url: '/invApplyIn',
    transferType: searchForm.transferType
  };
  proxy.$router.push({ path: '/invApplyInEdit', query: data });
}

function editInvOrderDialog() {
  if (!isEmpty(sltInvOrder.value)) {
    if (sltInvOrder.value.orderStatus == '10' || sltInvOrder.value.orderStatus == '15') {
      VxeMessage('该单据已验收不能修改', VxeNotifyType.info);
      return;
    }

    const data = {
      id: sltInvOrder.value.id,
      url: '/invApplyIn',
      transferType: searchForm.transferType
    };
    proxy.$router.push({ path: '/invApplyInEdit', query: data });
  } else {
    VxeMessage('无选中数据', VxeNotifyType.info);
  }
}
function checkInStock() {
  if (orderForm.orderStatus != '5') {
    VxeMessage('请选择未验收的单据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定验收入库？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const sltQcMaterials = [];
        sltQcMaterials.push(orderForm);
        const data = { invOrderInfoList: sltQcMaterials };
        const url = '/inv/orderInfo/batchAllotInStock';
        proxy.$http
          .post(url, data)
          .then((res: any) => {
            if (res.status.code === 1) {
              findInvOrderList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            } else {
              findInvOrderList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.error);
            }
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

function quietPrint() {
  //先根据路由的URL获取对应的报表信息
  const url = '/api/pubReport/getReportIdByUrl';
  proxy.$http
    .get(url, { params: { url: '/' + proxy.$route.name } })
    .then((res: any) => {
      const reportId = res.data;
      let arr = [];
      arr.push({
        ReportName: reportId,
        ReportParameters: [{ Name: 'Id', Value: sltInvOrder.value.id }],
        PdfPrinterSetting: { PdfPrinterCopies: 1 }
      });
      printParamsObj.value = arr;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

function previewPrint() {
  isPreviewRpt.value = false;
  //先根据路由的URL获取对应的报表信息
  const url = '/api/pubReport/getReportIdByUrl';
  proxy.$http
    .get(url, { params: { url: '/' + proxy.$route.name } })
    .then((res: any) => {
      const reportId = res.data;
      reportList.length = 0;
      const data = {
        id: sltInvOrder.value.id,
        reportTemplateName: '试剂耗材-调拨入库单.rdlx',
        reportId: reportId
      };
      reportList.push(data);
      isPreviewRpt.value = true;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

function formatCommon(arr: any, value: any) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}

function formatTransType(arr: any, value: any) {
  for (const item of arr) {
    if (item.transferCode == value) {
      return item.transferName;
    }
  }
}
function getStatusClass(row: any) {
  const status = row.orderStatus;
  if (status == '0') {
    return 'text-orange';
  } else if (status == '5') {
    return 'text-green';
  } else if (status == '10') {
    return 'text-orange';
  } else if (status == '15') {
    return 'text-blue';
  } else if (status == '20') {
    return 'text-black';
  }
}
</script>

<style lang="scss" scoped>
#invOrderlDiv {
  width: 100%;
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);
    // 右侧保存按钮
    .saveBtn {
      //float: right;
      margin: 0px 30px;
    }
    // 附加按钮间距
    .button-blue {
      margin: 5px 0 5px 5px;
    }
    .button-red {
      margin: 5px 0 5px 5px;
    }

    // 机构表格
    :deep(.vxe-table--render-default) {
      height: 100%;
    }
    :deep(.vxe-table--render-wrapper) {
      height: 100%;
      background-color: $base-white;
    }
    .tableBox {
      height: calc(100% - 40px);
    }
    .tableBoBox {
      height: calc(100% - 75px);
    }
    .horizontalLine {
      background-color: $base-white;
    }

    .searchform {
      padding: 10px 0 0 10px;

      :deep(.vxe-form--item) {
        margin-right: 30px;
      }
    }

    .searchform .vxe-input {
      --el-input-width: 120px;
    }

    .searchform .vxe-select {
      --el-select-width: 120px;
    }
    .form-input-m {
      .el-input {
        width: 150px;
      }

      .vxe-input {
        width: 150px !important;
      }
    }
  }
}
</style>
